package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.bwie.common.constants.Constants;
import com.bwie.common.domain.Organization;
import com.bwie.common.exceptions.BizExceptions;
import com.bwie.mapper.OrganizationMapper;
import com.bwie.service.OrganizationService;
import com.google.common.hash.BloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @className: OrganizationServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 汪菲阳
 * @date: 2025/10/22 12:08
 */
@Service
public class OrganizationServiceImpl implements OrganizationService {
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private BloomFilter<String> filter;

    @Override
    public void addOrganization(Organization organization) {
        //卫语句
        String organizationName = organization.getOrganizationName();
        //判断是否在过滤器中
        if (filter.mightContain(organizationName)){
            throw new BizExceptions(Constants.ORANGE_ADD_EXITS_CODE,Constants.ORANGE_ADD_EXITS_MSG);
        }
        //存入布隆过滤器
        filter.put(organizationName);
        String code = getCode();
        //赋值
        organization.setOrganizationCode(code);
        //进行添加
        organizationMapper.addOrangization(organization);
    }

    @Override
    public List<Organization> organizationList() {
        //查询所有的组织
        List<Organization> organizations = organizationMapper.selectALLOrange();
        Map<Integer, List<Organization>> collect = organizations
                .stream()
                .collect(Collectors.groupingBy(Organization::getOrganizationPid));
        List<Organization> organizationList=organizationTree(collect,0);
        return organizationList;
    }

    private List<Organization> organizationTree(Map<Integer, List<Organization>> collect, int pid) {
        List<Organization> organizations = collect.get(pid);
        organizations.forEach(organization -> {
            organization.setChildren(organizationTree(collect,organization.getOrganizationId()));
        });
        return organizations;
    }

    /**
     * 生成编码
     * @return
     */
    private String getCode(){
        //生成编码
        String num = RandomUtil.randomNumbers(4);
        String code="OR"+num;
        return code;
    }
}
